#!/usr/bin/env python

import re, os
import odb
# XXX this is lame
from modpy_stub import Request
import spudencfg

srcEnv = odb.Env(spudencfg.bdbPath)
dstEnv = odb.Env('tempdb', prefer = odb.MEM)

def moveTable(srcTab, dstTab):
   txn = None
   txnSize = 0
   for key, val in srcTab.cursor():

      # create a new transaction if we don't currently have one
      if not txn:
         txn = dstEnv.getTxn()

      dstTab.set(txn, key, val)

      # commit and free transactions when they start to get too big
      if txnSize > 1024:
         txn.commit()
         txn = None

class Table:
   def __init__(self, name, type):
      self.name = name
      self.type = type

# migrate each table
btreeRx = re.compile(r'.*Berkeley DB \(Btree')
hashRx = re.compile(r'.*Berkeley DB \(Hash')
for entry in os.listdir(spudencfg.bdbPath):
   cmdOut = \
      os.popen('file %s' % os.path.join(spudencfg.bdbPath, entry)).read()
   if btreeRx.match(cmdOut):
      srcTab = srcEnv.getBTreeDB(entry)
      dstTab = dstEnv.getBTreeDB(entry)
      moveTable(srcTab, dstTab)
   elif hashRx.match(cmdOut):
      srcTab = srcEnv.getBTreeDB(entry)
      dstTab = dstEnv.getBTreeDB(entry)
      moveTable(srcTab, dstTab)

